from datetime import datetime

from asgiref.sync import async_to_sync, sync_to_async
from openpyxl.reader.excel import load_workbook
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side

from allmodels.models import SysMenu, SysRoleMenu  # 假设所有模型都在 allmodels 中
from django.conf import settings
from login.views import verify_token  # 引入之前实现的验证 token 的函数
from allmodels.models import SysUser, SysDept, SysRole, SysUserRole  # 包含必要的模型
from django.db import transaction
import json
import openpyxl
from django.http import JsonResponse, HttpResponse
from rest_framework.views import APIView
from django.core.paginator import Paginator
from django.db.models import Q
from django.utils.timezone import localtime
from django.http import HttpResponse
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font, PatternFill
from django.core.files.storage import default_storage  # 导入 default_storage
from django.contrib.auth.hashers import make_password


class GetUserInfoView(APIView):
    @async_to_sync
    async def get(self, request, *args, **kwargs):
        return await self.get_user_info(request)

    @sync_to_async
    def model_get_user_info(self, access_token):
        # 解析令牌，获取 payload
        payload = verify_token(access_token)
        if 'error' in payload:
            return None, payload['error']  # 如果令牌无效，返回错误信息

        try:
            # 使用解析出的用户名查找用户
            username = payload.get('username')
            user = SysUser.objects.get(username=username)  # 获取 SysUser
            return user, None
        except SysUser.DoesNotExist:
            return None, 'User does not exist'

    @sync_to_async
    def get_user_roles(self, user_id):
        # 获取用户的角色 ID 和 code
        roles = SysRole.objects.filter(
            id__in=SysUserRole.objects.filter(user_id=user_id).values_list('role_id', flat=True))
        role_ids = roles.values_list('id', flat=True)  # 返回角色的ID
        role_codes = roles.values_list('code', flat=True)  # 返回角色的code
        return list(role_ids), list(role_codes)

    @sync_to_async
    def get_user_permissions(self, role_ids):
        # 获取角色对应的权限
        menu_ids = SysRoleMenu.objects.filter(role_id__in=role_ids).values_list('menu_id', flat=True)
        perms = SysMenu.objects.filter(id__in=menu_ids).values_list('perm', flat=True)
        return list(perms)

    async def get_user_info(self, request):
        # 从请求头中获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 获取用户信息
        user, error = await self.model_get_user_info(access_token)
        if error:
            return JsonResponse({
                'code': '10005',
                'msg': error
            }, status=401)

        # 获取用户角色和权限
        role_ids, role_codes = await self.get_user_roles(user.id)
        perms = await self.get_user_permissions(role_ids)

        # 返回用户信息
        return JsonResponse({
            "code": "00000",
            "data": {
                "userId": user.id,
                "username": user.username,
                "nickname": user.nickname or user.username,  # 如果没有昵称，使用用户名
                "avatar": user.avatar if user.avatar else "http://127.0.0.1:8000/media/defaults/default_avatar.gif",
                "roles": role_codes,  # 返回角色的 code
                "perms": perms  # 用户的权限列表
            },
            "msg": "操作成功"
        })


class GetUserPageView(APIView):
    @async_to_sync
    async def get(self, request, *args, **kwargs):
        return await self.get_user_page(request)

    @sync_to_async
    def model_get_user_page(self, keywords, status, dept_id, create_time, page_num, page_size):
        # 基于查询条件进行用户的筛选
        filters = Q()

        # 如果提供了关键字，则按用户名、昵称、手机号模糊查询
        if keywords:
            filters &= Q(username__icontains=keywords) | Q(nickname__icontains=keywords) | Q(mobile__icontains=keywords)

        # 如果提供了状态
        if status:
            filters &= Q(status=status)

        # 如果提供了部门 ID
        if dept_id:
            filters &= Q(dept_id=dept_id)

        # 创建时间范围（假设是一个起止时间的范围，格式处理略去）
        if create_time:
            # create_time 格式可以是 "start_time,end_time"
            start_time, end_time = create_time.split(',')
            filters &= Q(create_time__range=[start_time, end_time])

        # 进行分页查询
        users_query = SysUser.objects.filter(filters)
        paginator = Paginator(users_query, page_size)
        users_page = paginator.get_page(page_num)

        return list(users_page), paginator.count

    @sync_to_async
    def get_user_role_names(self, user_id):
        # 获取用户角色名称
        roles = SysRole.objects.filter(
            id__in=SysUserRole.objects.filter(user_id=user_id).values_list('role_id', flat=True))
        return ", ".join([role.name for role in roles])

    @sync_to_async
    def get_dept_name(self, dept_id):
        # 获取部门名称
        try:
            dept = SysDept.objects.get(id=dept_id)
            return dept.name
        except SysDept.DoesNotExist:
            return None

    async def get_user_page(self, request):
        # 获取查询参数
        keywords = request.GET.get('keywords', '')
        status = request.GET.get('status', '')
        dept_id = request.GET.get('deptId', '')
        create_time = request.GET.get('createTime', '')
        page_num = int(request.GET.get('pageNum', 1))
        page_size = int(request.GET.get('pageSize', 10))

        # 获取用户列表和总数
        users, total = await self.model_get_user_page(keywords, status, dept_id, create_time, page_num, page_size)

        # 生成用户信息列表
        user_list = []
        for user in users:
            role_names = await self.get_user_role_names(user.id)
            dept_name = await self.get_dept_name(user.dept_id)
            # 如果status为true则返回1反之0
            user.status = 1 if user.status else 0

            user_list.append({
                "id": user.id,
                "username": user.username,
                "nickname": user.nickname or user.username,  # 如果没有昵称，使用用户名
                "mobile": user.mobile,
                "genderLabel": "男" if user.gender == 1 else "女",
                "avatar": user.avatar or "https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif",
                # 默认头像
                "email": user.email,
                "status": user.status,
                "deptName": dept_name or "",
                "roleNames": role_names,
                "createTime": user.create_time.strftime('%Y-%m-%d') if user.create_time else None
            })

        # 返回分页结果
        return JsonResponse({
            "code": "00000",
            "data": {
                "list": user_list,
                "total": total
            },
            "msg": "一切ok"
        })


class CreateUserView(APIView):
    @async_to_sync
    async def post(self, request, *args, **kwargs):
        return await self.create_user(request)

    @sync_to_async
    def create_user_in_transaction(self, user_data, role_ids):
        try:
            with transaction.atomic():
                # 如果提供了ID且不为None或0，更新用户；否则创建新用户
                if 'id' in user_data and user_data['id']:  # 更新用户
                    user = SysUser.objects.get(id=user_data['id'])
                else:  # 创建新用户时，不需要设置ID，Django会自动分配
                    user = SysUser()

                # 设置用户数据
                user.username = user_data['username']
                user.nickname = user_data.get('nickname', user_data['username'])
                user.mobile = user_data.get('mobile', '')
                user.gender = user_data.get('gender', 1)  # 默认为1 (男)
                user.avatar = user_data.get('avatar', '')
                user.email = user_data.get('email', '')
                user.status = user_data.get('status', 1)  # 默认为1 (正常)
                user.dept_id = user_data.get('deptId')

                # 保存用户信息
                user.save()

                # 删除现有角色关联
                SysUserRole.objects.filter(user_id=user.id).delete()

                # 添加新角色关联
                for role_id in role_ids:
                    SysUserRole.objects.create(user_id=user.id, role_id=role_id)

            return user, None
        except Exception as e:
            return None, str(e)

    async def create_user(self, request):
        try:
            # 获取请求体中的JSON数据
            user_data = json.loads(request.body)

            # 验证请求中的角色ID集合是否存在
            if 'roleIds' not in user_data or not isinstance(user_data['roleIds'], list) or not user_data['roleIds']:
                return JsonResponse({
                    'code': '10001',
                    'msg': '角色ID集合不能为空'
                }, status=400)

            # 在同步的上下文中执行事务
            user, error = await self.create_user_in_transaction(user_data, user_data['roleIds'])
            if error:
                return JsonResponse({
                    'code': '10002',
                    'msg': f'用户创建: {error}'
                }, status=500)

            # 返回成功响应
            return JsonResponse({
                'code': '00000',
                'data': {
                    'userId': user.id,
                    'username': user.username,
                    'nickname': user.nickname,
                    'mobile': user.mobile,
                    'gender': user.gender,
                    'avatar': user.avatar,
                    'email': user.email,
                    'status': user.status,
                    'deptId': user.dept_id
                },
                'msg': '一切ok'
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10004',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10005',
                'msg': f'未知错误: {str(e)}'
            }, status=500)


class GetUserFormView(APIView):
    @async_to_sync
    async def get(self, request, user_id, *args, **kwargs):
        return await self.get_user_form(request, user_id)

    @sync_to_async
    def get_user(self, user_id):
        try:
            # 根据 user_id 获取用户信息
            user = SysUser.objects.get(id=user_id)
            return user, None
        except SysUser.DoesNotExist:
            return None, 'User does not exist'

    @sync_to_async
    def get_user_roles(self, user_id):
        # 获取用户角色ID集合
        role_ids = SysUserRole.objects.filter(user_id=user_id).values_list('role_id', flat=True)
        return list(role_ids)

    @sync_to_async
    def model_get_user_info(self, access_token):
        # 解析令牌，获取 payload
        payload = verify_token(access_token)
        if 'error' in payload:
            return None, payload['error']  # 如果令牌无效，返回错误信息

        try:
            # 使用解析出的用户名查找用户
            username = payload.get('username')
            user = SysUser.objects.get(username=username)  # 获取 SysUser
            return user, None
        except SysUser.DoesNotExist:
            return None, 'User does not exist'

    async def get_user_form(self, request, user_id):
        # 从请求头中获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌并获取用户信息
        auth_user, error = await self.model_get_user_info(access_token)
        if error:
            return JsonResponse({
                'code': '10005',
                'msg': error
            }, status=401)

        # 获取指定的用户信息
        user, error = await self.get_user(user_id)
        if error:
            return JsonResponse({
                'code': '10005',
                'msg': error
            }, status=404)

        # 获取用户角色ID集合
        role_ids = await self.get_user_roles(user.id)

        # 返回用户信息表单数据
        return JsonResponse({
            "code": "00000",
            "data": {
                "id": user.id,
                "username": user.username,
                "nickname": user.nickname or user.username,  # 如果没有昵称，使用用户名
                "mobile": user.mobile,
                "gender": user.gender,
                "avatar": user.avatar or "https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif",
                # 默认头像
                "email": user.email,
                "status": user.status,
                "deptId": user.dept_id,  # 部门ID
                "roleIds": role_ids  # 角色ID集合
            },
            "msg": "一切ok"
        })


class UpdateUserView(APIView):
    @async_to_sync
    async def put(self, request, user_id, *args, **kwargs):
        return await self.update_user(request, user_id)

    @sync_to_async
    def update_user_in_transaction(self, user_id, user_data, role_ids):
        try:
            with transaction.atomic():
                # 获取用户实例
                user = SysUser.objects.get(id=user_id)

                # 更新用户信息
                user.username = user_data.get('username', user.username)
                user.nickname = user_data.get('nickname', user.nickname)
                user.mobile = user_data.get('mobile', user.mobile)
                user.gender = user_data.get('gender', user.gender)
                user.avatar = user_data.get('avatar', user.avatar)
                user.email = user_data.get('email', user.email)
                user.status = user_data.get('status', user.status)
                user.dept_id = user_data.get('deptId', user.dept_id)

                # 保存更新后的用户信息
                user.save()

                # 更新用户角色关联
                SysUserRole.objects.filter(user_id=user.id).delete()  # 删除旧的角色关联
                for role_id in role_ids:
                    SysUserRole.objects.create(user_id=user.id, role_id=role_id)  # 创建新的角色关联

            return user, None
        except Exception as e:
            return None, str(e)

    @sync_to_async
    def model_get_user_info(self, access_token):
        # 解析令牌，获取 payload
        payload = verify_token(access_token)
        if 'error' in payload:
            return None, payload['error']  # 如果令牌无效，返回错误信息

        try:
            # 使用解析出的用户名查找用户
            username = payload.get('username')
            user = SysUser.objects.get(username=username)  # 获取 SysUser
            return user, None
        except SysUser.DoesNotExist:
            return None, 'User does not exist'

    async def update_user(self, request, user_id):
        # 从请求头中获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌并获取当前用户信息
        auth_user, error = await self.model_get_user_info(access_token)
        if error:
            return JsonResponse({
                'code': '10005',
                'msg': error
            }, status=401)

        try:
            # 获取请求体中的JSON数据
            user_data = json.loads(request.body)

            # 验证请求中的角色ID集合是否存在
            if 'roleIds' not in user_data or not isinstance(user_data['roleIds'], list) or not user_data['roleIds']:
                return JsonResponse({
                    'code': '10001',
                    'msg': '角色ID集合不能为空'
                }, status=400)

            # 在同步的上下文中执行更新操作
            user, error = await self.update_user_in_transaction(user_id, user_data, user_data['roleIds'])
            if error:
                return JsonResponse({
                    'code': '10002',
                    'msg': f'用户更新失败: {error}'
                }, status=500)

            # 返回成功响应
            return JsonResponse({
                'code': '00000',
                'data': {
                    'userId': user.id,
                    'username': user.username,
                    'nickname': user.nickname,
                    'mobile': user.mobile,
                    'gender': user.gender,
                    'avatar': user.avatar,
                    'email': user.email,
                    'status': user.status,
                    'deptId': user.dept_id
                },
                'msg': '用户更新成功'
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10004',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10005',
                'msg': f'未知错误: {str(e)}'
            }, status=500)


class DeleteUserView(APIView):
    @async_to_sync
    async def delete(self, request, *args, **kwargs):
        return await self.delete_users(request, *args, **kwargs)

    @sync_to_async
    def delete_users_in_transaction(self, user_ids):
        try:
            with transaction.atomic():
                # 如果 user_ids 是单个 ID，也应该将其转化为列表
                if isinstance(user_ids, str):
                    ids = [int(id.strip()) for id in user_ids.split(',')]

                # 批量删除用户
                SysUser.objects.filter(id__in=ids).delete()

            return None
        except Exception as e:
            return str(e)

    async def delete_users(self, request, *args, **kwargs):
        # 从 URL 路径中获取 'ids'
        user_ids = kwargs.get('ids', '')

        # 验证 user_ids 是否存在且非空
        if not user_ids:
            return JsonResponse({
                'code': '10001',
                'msg': '用户ID不能为空'
            }, status=400)

        # 从请求头中获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证 token
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': 'Token无效或已过期'
            }, status=401)

        # 在事务中删除用户
        error = await self.delete_users_in_transaction(user_ids)
        if error:
            return JsonResponse({
                'code': '10002',
                'msg': f'删除失败: {error}'
            }, status=500)

        # 返回成功响应
        return JsonResponse({
            'code': '00000',
            'data': {},
            'msg': '删除成功'
        })


class ExportUserExcelView(APIView):
    @async_to_sync
    async def get(self, request, *args, **kwargs):
        return await self.export_users(request)

    @sync_to_async
    def model_get_users(self):
        # 查询所有用户以及关联的角色和部门信息
        users = SysUser.objects.all()
        user_list = []
        for user in users:
            role_names = SysRole.objects.filter(
                id__in=SysUserRole.objects.filter(user_id=user.id).values_list('role_id', flat=True))
            roles = ", ".join([role.name for role in role_names])

            dept_name = ""
            if user.dept_id:
                dept = SysDept.objects.filter(id=user.dept_id).first()
                dept_name = dept.name if dept else ""

            user_list.append({
                "username": user.username,
                "nickname": user.nickname or user.username,
                "deptName": dept_name,
                "genderLabel": "男" if user.gender == 1 else "女",
                "mobile": user.mobile,
                "email": user.email or '',
                "createTime": localtime(user.create_time).strftime('%Y/%m/%d %H:%M:%S') if user.create_time else '',
                "roles": roles
            })

        return user_list

    async def export_users(self, request):
        # Token 验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': 'Token无效或已过期'
            }, status=401)

        # 获取用户数据
        user_list = await self.model_get_users()

        # 创建 Excel 工作簿
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "用户数据"

        # 美化表头
        headers = ["用户名", "用户昵称", "部门", "性别", "手机号码", "邮箱", "创建时间", "角色"]
        ws.append(headers)

        # 设置列宽
        ws.column_dimensions['A'].width = 15
        ws.column_dimensions['B'].width = 20
        ws.column_dimensions['C'].width = 15
        ws.column_dimensions['D'].width = 10
        ws.column_dimensions['E'].width = 15
        ws.column_dimensions['F'].width = 25
        ws.column_dimensions['G'].width = 20
        ws.column_dimensions['H'].width = 25

        # 设置表头样式
        font = Font(bold=True, color="FFFFFF")
        alignment = Alignment(horizontal="center", vertical="center")
        for cell in ws[1]:  # 第1行的所有单元格
            cell.font = font
            cell.alignment = alignment
            cell.fill = openpyxl.styles.PatternFill(start_color="4F81BD", end_color="4F81BD", fill_type="solid")

        # 填充数据
        for user in user_list:
            ws.append([
                user['username'],
                user['nickname'],
                user['deptName'],
                user['genderLabel'],
                user['mobile'],
                user['email'],
                user['createTime'],
                user['roles']
            ])

        # 自动调整行高
        for row in ws.iter_rows():
            for cell in row:
                cell.alignment = Alignment(horizontal='center', vertical='center')

        # 返回 Excel 文件
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'attachment; filename="用户数据.xlsx"'

        wb.save(response)
        return response


class GenerateUserTemplateView(APIView):

    def get(self, request, *args, **kwargs):
        # 从请求头中获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 生成并返回 Excel 模板
        return self.generate_user_template()

    def generate_user_template(self):
        # 创建 Excel 工作簿
        wb = Workbook()
        ws = wb.active
        ws.title = "用户导入模板"

        # 表头字段
        headers = ["用户名", "昵称", "性别", "手机号码", "邮箱", "角色", "部门"]
        ws.append(headers)

        # 设置列宽
        ws.column_dimensions['A'].width = 15
        ws.column_dimensions['B'].width = 20
        ws.column_dimensions['C'].width = 10
        ws.column_dimensions['D'].width = 15
        ws.column_dimensions['E'].width = 25
        ws.column_dimensions['F'].width = 20
        ws.column_dimensions['G'].width = 20

        # 设置表头样式
        header_font = Font(bold=True, color="000000")  # 黑色字体
        header_fill = PatternFill(start_color="C0C0C0", end_color="C0C0C0", fill_type="solid")  # 灰色背景
        header_alignment = Alignment(horizontal="center", vertical="center")

        # 应用样式到表头
        for cell in ws[1]:  # 第1行的所有单元格
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = header_alignment

        # 返回 Excel 文件
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = f'attachment; filename="users_{datetime.now().strftime("%Y%m%d%H%M%S")}.xlsx"'
        wb.save(response)

        return response


class ImportUsersView(APIView):

    def post(self, request, *args, **kwargs):
        # 从请求头中获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取部门 ID
        dept_id = request.GET.get('deptId')
        if not dept_id:
            return JsonResponse({
                'code': '10006',
                'msg': '部门 ID 不能为空'
            }, status=400)

        # 检查上传的文件是否存在
        if 'file' not in request.FILES:
            return JsonResponse({
                'code': '10007',
                'msg': '文件上传失败，未提供文件'
            }, status=400)

        # 读取上传的 Excel 文件
        file = request.FILES['file']
        file_path = default_storage.save(f'temp/{file.name}', file)  # 保存到临时目录
        file_full_path = default_storage.path(file_path)

        # 开始处理 Excel 文件
        try:
            wb = openpyxl.load_workbook(file_full_path)
            sheet = wb.active  # 获取第一个工作表
        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'文件读取失败: {str(e)}'
            }, status=400)

        # 逐行处理数据
        users = []
        errors = []  # 用于记录错误的用户名
        try:
            with transaction.atomic():
                for row in sheet.iter_rows(min_row=2, values_only=True):  # 从第 2 行开始读取
                    username, nickname, gender, mobile, email, role_name, dept_name = row

                    # 检查用户名是否已经存在
                    if SysUser.objects.filter(username=username).exists():
                        errors.append(f'用户名 {username} 已存在，跳过该用户')
                        continue  # 跳过该用户

                    # 创建新用户
                    user = SysUser(
                        username=username,
                        nickname=nickname,
                        gender=gender,
                        mobile=mobile,
                        email=email,
                        dept_id=dept_id,
                        create_time=datetime.now()  # 设置创建时间
                    )
                    user.save()

                    # 查找角色
                    role = SysRole.objects.filter(name=role_name).first()
                    if role:
                        # 绑定用户和角色
                        SysUserRole.objects.create(user_id=user.id, role_id=role.id)

                    users.append(user)

        except Exception as e:
            return JsonResponse({
                'code': '10009',
                'msg': f'用户导入失败: {str(e)}'
            }, status=500)

        # 返回成功响应
        return JsonResponse({
            'code': '00000',
            'msg': '用户导入成功',
            'data': {
                'imported_users': len(users),
                'errors': errors  # 返回跳过的用户信息
            }
        })


class ResetUserPasswordView(APIView):
    def patch(self, request, *args, **kwargs):
        # 从请求头中获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性，获取用户 ID
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        user_id = payload.get('user_id')  # 从 token payload 获取用户 ID

        # 检查请求体是否为空
        if not request.body:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体不能为空'
            }, status=400)

        # 尝试解析请求体中的数据
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        old_password = data.get('oldPassword')
        new_password = data.get('newPassword')
        confirm_password = data.get('confirmPassword')

        # 检查是否提供了所有必要的字段
        if not all([old_password, new_password, confirm_password]):
            return JsonResponse({
                'code': '10008',
                'msg': '缺少必要的字段'
            }, status=400)

        # 检查新密码和确认密码是否匹配
        if new_password != confirm_password:
            return JsonResponse({
                'code': '10009',
                'msg': '新密码和确认密码不匹配'
            }, status=400)

        # 查找用户并验证旧密码
        try:
            user = SysUser.objects.get(id=user_id)

            # 验证旧密码是否正确
            if not user.check_password(old_password):
                return JsonResponse({
                    'code': '10010',
                    'msg': '旧密码不正确'
                }, status=400)

            # 更新为新密码
            user.password = make_password(new_password)  # 使用 make_password 进行密码加密
            user.save()

            return JsonResponse({
                'code': '00000',
                'msg': '密码重置成功'
            })
        except SysUser.DoesNotExist:
            return JsonResponse({
                'code': '10011',
                'msg': '用户不存在'
            }, status=404)
        except Exception as e:
            return JsonResponse({
                'code': '10012',
                'msg': f'未知错误: {str(e)}'
            }, status=500)


# 重置用户密码
class ResetUserAllPasswordView(APIView):
    def put(self, request, *args, **kwargs):
        # 从 URL 路径中获取用户ID
        user_id = kwargs.get('user_id')  # 确保从路径参数中提取用户ID

        # 检查是否提供了用户ID
        if not user_id:
            return JsonResponse({
                'code': '10006',
                'msg': '用户ID不能为空'
            }, status=400)

        # 从查询参数中获取新密码
        new_password = request.GET.get('password')
        if not new_password:
            return JsonResponse({
                'code': '10007',
                'msg': '新密码不能为空'
            }, status=400)

        # 查找用户并重置密码
        try:
            user = SysUser.objects.get(id=user_id)
            user.password = make_password(new_password)  # 使用 make_password 进行密码加密
            user.save()

            return JsonResponse({
                'code': '00000',
                'msg': '密码重置成功'
            })
        except SysUser.DoesNotExist:
            return JsonResponse({
                'code': '10009',
                'msg': '用户不存在'
            }, status=404)
        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)


class UpdateUserStatusView(APIView):
    def patch(self, request, *args, **kwargs):
        # 从请求头中获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取路径参数中的用户ID
        user_id = kwargs.get('userId')
        if not user_id:
            return JsonResponse({
                'code': '10006',
                'msg': '用户ID不能为空'
            }, status=400)

        # 获取查询参数中的状态
        new_status = request.GET.get('status')
        if new_status is None:
            return JsonResponse({
                'code': '10007',
                'msg': '用户状态不能为空'
            }, status=400)

        try:
            new_status = int(new_status)  # 确保状态为整数
            if new_status not in [0, 1]:
                return JsonResponse({
                    'code': '10008',
                    'msg': '无效的状态值'
                }, status=400)
        except ValueError:
            return JsonResponse({
                'code': '10008',
                'msg': '状态值必须为整数'
            }, status=400)

        # 查找用户并更新状态
        try:
            user = SysUser.objects.get(id=user_id)
            user.status = new_status  # 更新用户状态
            user.save()

            return JsonResponse({
                'code': '00000',
                'msg': '用户状态更新成功'
            })
        except SysUser.DoesNotExist:
            return JsonResponse({
                'code': '10009',
                'msg': '用户不存在'
            }, status=404)
        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)


class UserProfileView(APIView):
    def get(self, request, *args, **kwargs):
        # 从请求头中获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性，获取用户 ID
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        user_id = payload.get('user_id')  # 从 token payload 获取用户 ID

        # 查询用户信息
        try:
            user = SysUser.objects.get(id=user_id)
        except SysUser.DoesNotExist:
            return JsonResponse({
                'code': '10006',
                'msg': '用户不存在'
            }, status=404)

        # 获取部门名称
        dept_name = SysDept.objects.filter(id=user.dept_id).values_list('name',
                                                                        flat=True).first() if user.dept_id else None

        # 获取用户角色
        roles = SysRole.objects.filter(
            id__in=SysUserRole.objects.filter(user_id=user.id).values_list('role_id', flat=True)
        )
        role_names = ', '.join([role.name for role in roles])

        # 返回用户信息
        return JsonResponse({
            "code": "00000",
            "data": {
                "id": user.id,
                "username": user.username,
                "nickname": user.nickname or user.username,  # 如果没有昵称，使用用户名
                "avatar": user.avatar or "https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif",  # 默认头像
                "gender": user.gender,
                "mobile": user.mobile,
                "email": user.email,
                "deptName": dept_name or "",
                "roleNames": role_names,
                "createTime": user.create_time.strftime('%Y-%m-%d') if user.create_time else None
            },
            "msg": "一切ok"
        })


class UpdateUserProfileView(APIView):
    def put(self, request, *args, **kwargs):
        # 从请求头中获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性，获取用户 ID
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        user_id = payload.get('user_id')  # 从 token payload 获取用户 ID

        # 获取请求体中的数据
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        # 查找用户
        try:
            user = SysUser.objects.get(id=user_id)
        except SysUser.DoesNotExist:
            return JsonResponse({
                'code': '10008',
                'msg': '用户不存在'
            }, status=404)

        # 更新用户信息
        user.username = data.get('username', user.username)
        user.nickname = data.get('nickname', user.nickname)
        user.avatar = data.get('avatar', user.avatar)
        user.gender = data.get('gender', user.gender)
        user.mobile = data.get('mobile', user.mobile)
        user.email = data.get('email', user.email)

        try:
            user.save()

            # 返回更新后的用户信息
            return JsonResponse({
                'code': '00000',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'nickname': user.nickname,
                    'avatar': user.avatar,
                    'gender': user.gender,
                    'mobile': user.mobile,
                    'email': user.email,
                    'deptName': user.dept.name if user.dept else None,  # 假设有部门信息
                    'createTime': user.create_time.strftime('%Y-%m-%d %H:%M:%S') if user.create_time else None
                },
                'msg': '一切ok'
            })
        except Exception as e:
            return JsonResponse({
                'code': '10009',
                'msg': f'更新失败: {str(e)}'
            }, status=500)



class ImportUsersView1(APIView):
    def post(self, request, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 检查上传的文件是否存在
        if 'file' not in request.FILES:
            return JsonResponse({
                'code': '10006',
                'msg': '文件上传失败，未提供文件'
            }, status=400)

        # 读取上传的 Excel 文件
        file = request.FILES['file']
        file_path = default_storage.save(f'temp/{file.name}', file)  # 保存到临时目录
        file_full_path = default_storage.path(file_path)

        # 开始处理 Excel 文件
        try:
            wb = load_workbook(file_full_path)
            sheet = wb.active  # 获取第一个工作表
        except Exception as e:
            return JsonResponse({
                'code': '10007',
                'msg': f'文件读取失败: {str(e)}'
            }, status=400)

        # 逐行处理数据
        users = []
        try:
            with transaction.atomic():
                for row in sheet.iter_rows(min_row=2, values_only=True):  # 从第 2 行开始读取
                    username, nickname, gender, mobile, email, role_name, dept_name = row

                    # 根据用户名查找用户，若不存在则创建
                    user, created = SysUser.objects.get_or_create(username=username)
                    user.nickname = nickname
                    user.gender = gender
                    user.mobile = mobile
                    user.email = email
                    user.dept_id = dept_name  # 假设 dept_name 是部门ID
                    user.save()

                    # 查找角色
                    role = SysRole.objects.filter(name=role_name).first()
                    if role:
                        # 绑定用户和角色
                        SysUserRole.objects.create(user_id=user.id, role_id=role.id)

                    users.append(user)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'用户导入失败: {str(e)}'
            }, status=500)

        # 返回成功响应
        return JsonResponse({
            'code': '00000',
            'msg': '用户导入成功',
            'data': {'imported_users': len(users)}
        })


class ExportUsersView1(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取查询参数
        keywords = request.GET.get('keywords', '')
        status = request.GET.get('status', '')
        dept_id = request.GET.get('deptId', '')
        create_time = request.GET.get('createTime', '')
        page_num = int(request.GET.get('pageNum', 1))
        page_size = int(request.GET.get('pageSize', 10))

        # 构建查询条件
        filters = Q()
        if keywords:
            filters &= Q(username__icontains=keywords) | Q(nickname__icontains=keywords) | Q(mobile__icontains=keywords)

        if status:
            filters &= Q(status=status)

        if dept_id:
            filters &= Q(dept_id=dept_id)

        if create_time:
            start_time, end_time = create_time.split(',')
            filters &= Q(create_time__range=[start_time, end_time])

        # 查询用户
        users_query = SysUser.objects.filter(filters).order_by('create_time')
        paginator = Paginator(users_query, page_size)
        users_page = paginator.get_page(page_num)

        # 创建 Excel 工作簿
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "用户数据"

        # 美化样式
        header_font = Font(bold=True, color="FFFFFF")
        header_fill = PatternFill(start_color="4F81BD", end_color="4F81BD", fill_type="solid")
        alignment_center = Alignment(horizontal="center", vertical="center")
        thin_border = Border(left=Side(style="thin"), right=Side(style="thin"), top=Side(style="thin"), bottom=Side(style="thin"))

        # 添加标题行
        headers = ["用户名", "昵称", "部门", "性别", "手机号码", "邮箱", "创建时间"]
        ws.append(headers)

        # 美化标题行
        for col in ws.iter_cols(min_row=1, max_row=1, min_col=1, max_col=len(headers)):
            for cell in col:
                cell.font = header_font
                cell.fill = header_fill
                cell.alignment = alignment_center
                cell.border = thin_border

        # 填充数据
        for user in users_page:
            dept_name = SysDept.objects.get(id=user.dept_id).name if user.dept_id else "无部门"
            gender = "男" if user.gender == 1 else "女"
            row = [
                user.username,
                user.nickname or user.username,
                dept_name,
                gender,
                user.mobile,
                user.email or "无",
                user.create_time.strftime('%Y-%m-%d %H:%M:%S') if user.create_time else "无"
            ]
            ws.append(row)

        # 美化数据行
        for row in ws.iter_rows(min_row=2, max_row=ws.max_row, min_col=1, max_col=len(headers)):
            for cell in row:
                cell.alignment = alignment_center
                cell.border = thin_border

        # 自动调整列宽
        for col in ws.columns:
            max_length = 0
            column = col[0].column_letter  # 获取列字母
            for cell in col:
                try:
                    if len(str(cell.value)) > max_length:
                        max_length = len(str(cell.value))
                except:
                    pass
            adjusted_width = (max_length + 2)
            ws.column_dimensions[column].width = adjusted_width

        # 设置响应内容为 Excel 文件
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = f'attachment; filename="users_{datetime.now().strftime("%Y%m%d%H%M%S")}.xlsx"'

        # 保存 Excel 文件到响应中
        wb.save(response)

        return response
